/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: TaskCtrl_Dummy.cpp,v 1.5 2009-10-09 10:55:28 mmatusia Exp $
 *
 * \file
 * \brief TaskCtrl interface dummy server module.
 * \author Antti Maula <antti.maula@tkk.fi>, Marek Matusiak
 *
 ******************************************************************************
 * NOTE: The following 'Module Info' should be kept up-to-date. Do NOT
 * change its format, insert your information according to the template.
 ******************************************************************************
 * Module Info:
 *
 * Uses drivers:
 *
 * Provides Interfaces:
 * - TaskCtrl
 *
 * Needs Interfaces:
 *
 * General information:
 * 
 ******************************************************************************
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "owndebug.h"
#include "ownutils.h"
#include "settings.hpp"
#include "binbag.h"
#include "TaskCtrlServer.hpp"

//*****************************************************************************

// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************

// Set initial verbosity level to ODINFO
static int verbose = ODINFO;
//*****************************************************************************

// Choose your namespace
using namespace MaCI;
using namespace MaCI::TaskCtrl;
//*****************************************************************************

// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************

// GIMnet parameters
static std::string gimnetAP = "asrobo.hut.fi";
static int gimnetAPPort = 50002;
static std::string gimnetName;
static std::string macigroup;
// Configuration parameters
static std::string configurationFile;
//*****************************************************************************

// Local configuration structure
struct SLocalConfig {
  SLocalConfig()
    : myparameter("SomeDefaultValue") {}
  std::string myparameter;
};
//*****************************************************************************

// Local configuration here. (Encapsulated in struct to make it easier
// to pass around)
SLocalConfig localConfig;
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(ODSTATUS,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(ODSTATUS,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
//*****************************************************************************

/**
 * All MaCI modules should support these parameters with exactly these names
 * *** DO NOT CHANGE NOR DELETE ANY OF THEM ***
 * Howevery, feel free to add new parameters as you wish.
 */
static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tTaskCtrl_Dummy [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-f conf_file]\t\tUse 'conf_file' as configuration file for this module\n");
  fprintf(stderr,"  [-G name]\t\t\tSpecify the MaCIGroup for this module\n");
  
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

static int taskctrlWatch(CTaskCtrlServer *ds)
{
    CTaskCtrlData dd;
    SMessageSource ms;
    CTaskCtrlData dataOut;
    EMaCIError e;
    dataOut.CreateInternalBinBag();
    //Server side parser example:
    while(run) {
        e = ds->WaitCommand(dd, ms, 1000);
        dataOut.Reset();
        if (e == KMaCIOK) {
            const TCommand *c = dd.GetCommand();
            TCommand replyCmd;
            replyCmd.cmd = c->cmd;
            replyCmd.flags = KCommandFlagReply;
            replyCmd.taskID = c->taskID;
            replyCmd.cmd = c->commandID;
            
            if (c) {
                dPrint(2,"Got command: %d, data %d, taskID_major0 = %u, taskID_minor0 = %u, taskID_minor1 = %u, taskID_minor2 = %u, commandID %d", c->cmd, c->flags, c->taskID.major0, c->taskID.minor0,c->taskID.minor1,c->taskID.minor2,c->commandID);

                switch (c->cmd) {                
                        
                    case KCommandAddTask: {
                        dPrint(1,"KCommandAddTask");
                        if (!dd.GetTaskCtrlXMLPtrArray().empty()) {
                            dPrint(1,"Got some XML!");
                        }
                        else {
                            dPrint(1,"Got command but no XML!");
                        }
                        dataOut.SetCommand(replyCmd);                         
                        break;
                    }
                    case KCommandRemoveTask: {
                        dPrint(1,"KCommandRemoveTask.\n");
                        dataOut.SetCommand(replyCmd);             
                        break;
                    }
                    case KCommandSetTaskState: {
                        dPrint(1,"KCommandSetTaskState\n");
                        if (dd.GetTaskCtrlStateCommand()!=NULL) {
                            dPrint(1,"Got GetTaskCtrlStateCommand!");
                        }
                        else {
                            dPrint(1,"Got command but no GetTaskCtrlStateCommand!");
                        }
                        dataOut.SetCommand(replyCmd);             
                        break;
                    }
                    case KCommandGetTaskState: {
                        dPrint(1,"KCommandGetTaskState\n");
                        dataOut.SetCommand(replyCmd); 
                        TTaskCtrlTaskID id(c->taskID.major0, c->taskID.minor0,c->taskID.minor1,c->taskID.minor2,c->taskID.bundleID);
                        //3442 ETC and 33.98% complete
                        bool r =dataOut.SetTaskCtrlTaskState(MaCI::TaskCtrl::TTaskCtrlTaskState(id, KTaskStateRunning,3442,33.98));
                        dPrint(1,"Setting ? %d",r);
                        //                        dataOut.AddTaskCtrlXMLString("<TaskState>diibadaabadaa</TaskState>");        
                        break;
                    }
                    case KCommandGetTask: {
                        dPrint(1,"KCommandGetTask");
                        dataOut.SetCommand(replyCmd);   
                        dataOut.AddTaskCtrlXMLString("<Taskinfo>AutoMagic</Taskinfo>");        
                        break;
                    }
                    case KCommandGetCompetences: {
                        dPrint(1,"KCommandGetCompetences");
                        dataOut.SetCommand(replyCmd);   
                        dataOut.AddTaskCtrlXMLString("<Competences>Levitation</Competences>");        
                        break;
                    }
                    case KCommandEvaluateTask: {
                        dPrint(1,"KCommandEvaluateTask");
                        if (!dd.GetTaskCtrlXMLPtrArray().empty()) {
                            dPrint(1,"Got some XML!");
                            dataOut.SetCommand(replyCmd);   
                                for(EACH_IN_i(dd.GetTaskCtrlXMLPtrArray())) {
                                    dataOut.AddTaskCtrlEvaluation(TTaskCtrlEvaluation(replyCmd.taskID, 1, 233.90, 4000));
                                }       
                        }
                        else {
                            dPrint(1,"Got command but no XML!");
                        }            
                        break;
                                      
                    }
    
                    case KCommandStatusEvent: {
                        dPrint(1,"KCommandStatusEvent. Server side should not get this? Sending helpful up yours- message.");
                        replyCmd.flags = KCommandFlagNotSupported;
                        dataOut.SetCommand(replyCmd);                               
                        break;
                    }
                    default: {
                        dPrint(1,"Got command crap. You suck! Sending up yours message.");
                        replyCmd.flags = KCommandFlagNotSupported;  
                        dataOut.SetCommand(replyCmd);                             
                        break;
                    }            
                }
                dd.Print(1);
                dPrint(1,"Printing generated outgoing container.");
                dataOut.Print(1);
                //send reply to synch. message
                ds->SendReply(dataOut, ms);
                
            } else {
            dPrint(ODERROR,"Got Command, but no Command element present???");

            }
        }
        else {
            dPrint(ODSTATUS,"No command received");
        }
    }



    return 0;
}
//*****************************************************************************

static int ExecuteModule(gimi::GIMI &g)
{
  // Construct an MaCICtrlServer instance
  MaCICtrl::CMaCICtrlServer mcs(&g, 0);

  // Construct instance of TaskCtrlServer
  CTaskCtrlServer ds(&mcs, 0, "TaskCtrl serviizi", "TaskCtrl_Dummy");

  // Construct instance of TaskCtrlData && Init to use internal BinBag
  CTaskCtrlData dd;
  dd.CreateInternalBinBag();

  // Create alarm data.
  Alarm::CAlarmData ad;
  ad.CreateInternalBinBag();

  // Set GroupName for MaCICtrlServer and Instance for AlarmServer.
  mcs.SetGroupName(macigroup);
  ds.SetInterfaceInstanceName("TaskCtrlInstance");

  // Init random number generator
  srandom(time(NULL));
  
  // Enable the Reporting interface.
  ds.EnableAlarmServer();
  assert(ds.GetAlarmServerPtr() != NULL);

  // Create command watch.
  ownThreadHandle taskctrlWatchThread;

  if (ds.Open() == KMaCIOK) {
    // Run!
    taskctrlWatchThread = ownThread_Create((void*)taskctrlWatch, &ds);

    // At this point, we have a preconnected GIMI, so now its up to you
    // to do things.  For more examples of functionality and structure,
    // see other MaCI modules, such as Alarm_TaskCtrl.cpp.
    while(run) {
      const unsigned int rvalue = random();
      dd.Reset();
      
      // Set timestamp to current (default constructor of Common::TTimestamp)
      dd.SetTimestamp(Common::TTimestamp());
      //Add a status event
      dd.SetTaskCtrlStatusEvent(TTaskCtrlStatusEvent(12, KTaskStateUnknown, 100000, 0.0));
      //Send event!
      ds.SendTaskCtrlStatusEvent(dd);
      
      // Wait a second + random()
      dPrint(ODVINFO,"ownSleep_ms(%d)", 1000+(rvalue%1000));
      ownSleep_ms(1000 + (rvalue % 1000));
    }

    // Add a call to gimi:stop()
    g.stop();

    // wait until the command handling thread terminates.
    ownThread_Join(taskctrlWatchThread, NULL);

  } else {
    dPrint(ODERROR,"Failed to open CTaskCtrlServer instance! Fatal error.");
    return -1;

  }
  

  return 0;
}
//*****************************************************************************

static bool ParseConfiguration(SLocalConfig &aConf,
                               const std::string &aConfigFile)
{ 
  gim::CSettings settings;
  bool result = settings.ReadSettingsXMLFile(aConfigFile);
  
  // Was the file succesfully parsed?
  if (result) {
    bool r;

    // Set basekey.
    settings.SetBaseKey("My_Module_Name");

    // Start extracting parameters. Duplicate this to extract
    // more. The print is just for verbalizing the output, so use it
    // if you want.
    r = settings.GetValue("myparameter", aConf.myparameter);
    if (r) { dPrint(ODVINFO,"Got configuration value for 'MyParameter' = '%s'", aConf.myparameter.c_str()); } 
    else { dPrint(ODVINFO,"No configuration value for 'MyParameter'"); }

    // Modify 'result', for example, if you want to force some parameters to
    // exists or pass some other quality check.
  }
  
  return result;
}
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(verbose);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
	  "\n%s - $Revision: 1.5 $\n", argv[0]);

  /////////////////////////////////////////////////////////////////////////////
  // Parse parameters - Remember: ** DO NOT MODIFY OR DELETE ANY OF THIS **
  // _Add_ anything as you wish.
  ///////////////////////////////////////////////////////////////////////////// 
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "f:n:u:p:G:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////

      /////////////////////////////////
      ///// MaCI/GIMnet parameters ////
      /////////////////////////////////
    case 'f':
      configurationFile = optarg;
      dPrint(ODVINFO,"Using configuration file: '%s'", optarg);
      if (ParseConfiguration(localConfig, configurationFile) == true) {
        dPrint(4,"Succesfully parsed configuration file '%s'", optarg);
      } else {
        dPrint(ODERROR,"Parsing configuration failed! Fatal error. Exit.");
        exit(1);
      }
      break;

    case 'n':
      gimnetName = optarg;
      dPrint(ODVINFO,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(ODVINFO,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(ODVINFO,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

    case 'G':
      macigroup = optarg;
      dPrint(ODVINFO,"Using MaCI-Group '%s'", optarg);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(ODERROR,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(ODINFO,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    // GIMnet connection OK, now execute module.
    r = ExecuteModule(g);
  }

  return 0;
}
//*****************************************************************************
//*****************************************************************************
/******************************************************************************
 * 
 * $Log: not supported by cvs2svn $
 * Revision 1.4  2009-09-18 09:56:35  mmatusia
 * jee
 *
 * Revision 1.3  2009-09-18 08:05:27  mmatusia
 * Implemented a ProcessMessage-type-parser in the dummy. Will need to think
 * about whether it is feasible to implement in the TaskCtrlServer as well.
 *
 * Revision 1.2  2009-08-31 13:25:03  mmatusia
 * Added handling of synchronous comms
 *
 * Revision 1.1  2009-05-06 07:57:05  amaula
 * Some work  for the TaskCtrl interface
 *
 * Revision 1.7  2009-02-09 10:24:36  amaula
 * Cleaned up a little.
 *
 * Revision 1.6  2009-01-19 11:59:05  amaula
 * Merged in branch: 'MaCI-interfaces-synchronous-messaging-replyQueue-implementation-branch'
 *
 * Revision 1.5.4.2  2009-01-19 11:45:20  amaula
 * Example Implementation for Synchronous messages complete.
 *
 * Revision 1.5.4.1  2009-01-19 07:51:44  amaula
 * Added call to gimi.stop().
 *
 * Revision 1.5  2008-12-22 13:24:00  amaula
 * Added example of using the integrated Alarm interface in MaCI.
 *
 * Revision 1.4  2008-12-01 10:26:28  amaula
 * Some more example code added.
 *
 * Revision 1.3  2008-12-01 10:14:32  amaula
 * Added more demo options.
 *
 * Revision 1.2  2008-12-01 10:01:31  amaula
 * Cleanup
 *
 * Revision 1.1  2008-12-01 10:00:00  amaula
 * Added pure taskctrl module.
 *
 *****************************************************************************/
//*****************************************************************************
//*****************************************************************************


